package org.streets.eis.component.organtree;

import java.util.List;

import org.apache.wicket.util.string.Strings;
import org.streets.database.Limits;
import org.streets.eis.EisWebSession;
import org.streets.eis.component.tree.Node;
import org.streets.eis.entity.Organization;
import org.streets.eis.entity.User;
import org.streets.eis.types.UnitType;

public class CompanyTree extends OrganTree{
	
	private static final long serialVersionUID = 1L;

	public CompanyTree(String id){
		super(id);
	}
	
	public CompanyTree(String id, boolean showCheckBox){
		super(id,showCheckBox);
	}	
	
	@Override
	protected void loadChildNode(Node<Organization> node){
		
		String parentId = node.getObject().getId();
		
		String organSql  = "";
		
		User user = EisWebSession.get().getUser(); //获取当前用户
		
		String userOrganSql = authorizer.generateUserOrganPermitSql(user);
		
		String attrSql = String.format("(ATTR='%s' or ATTR='%s')",UnitType.GROUP.value(),UnitType.COMPANY.value());
		
		if (Strings.isEmpty(parentId)){
			boolean flag = rootNodeIds!=null && rootNodeIds.length>0;
			if (flag){ 
				organSql = String.format("SELECT * FROM EIS_ORGAN WHERE %s AND %s AND ID IN (%s)  ORDER BY SHOW_INDEX",
						attrSql,generateSqlOR("ID",rootNodeIds),userOrganSql);
				flag = connection.count(organSql) > 0;
			}
			if (!flag) {
				organSql = String.format("SELECT * FROM EIS_ORGAN WHERE  %s AND ID IN (%s) AND nvl(PARENT_ID,'#') NOT IN (%s)  ORDER BY SHOW_INDEX",
					attrSql,userOrganSql,userOrganSql);	
			}
		} else {
			organSql = String.format("SELECT * from EIS_ORGAN WHERE PARENT_ID='%s' AND %s AND ID IN (%s) ORDER BY SHOW_INDEX",
					parentId,attrSql,userOrganSql);
		}
		
		List<Organization> children = connection.query(organSql,Organization.class,Limits.none());
		for (Organization child : children){
			node.add(new Node<Organization>(child));
		}		
	}	
}
